package com.example.contract.sendnft;

import com.example.contract.service.SendNftAddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.DefaultGasProvider;

import java.math.BigInteger;
import java.util.List;

@Component
public class SendNft {
    //合约地址
    private static final String CONTRACT_ADDRESS = "0x82F3Ffe3675a790aC57F3Fed4838770B8917515B";

    //部署合约的私钥
    private static final String PRIVATE_KEY = "6c66fe51db46ea88b67ea2ec517bc5f0a565a9c85cd884e2b345c070e57363a5";
    private static final String NODE_URL = "https://zitcoin.us/";

    @Autowired
    SendNftAddService sendNftAddService;

    public String sendNft(String address, String img) {
//        List<String> imageAll = sendNftAddService.findImageAll();
        // 初始化Web3j服务
        Web3j web3j = Web3j.build(new HttpService(NODE_URL));
        // 加载你的Ethereum钱包凭证
        Credentials credentials = Credentials.create(PRIVATE_KEY);
        // 创建TransactionManager
        TransactionManager transactionManager = new RawTransactionManager(
                web3j, credentials, Long.valueOf(9998)
        );
        // 加载你的智能合约
        Nft contract = Nft.load(
                CONTRACT_ADDRESS, web3j, transactionManager, new DefaultGasProvider());
        String recipientAddress = address;
        try {
            // 调用合约的safeMint函数
            String[] split = img.split(".png");
            BigInteger tokenId = new BigInteger(String.valueOf(split[0]));
            String url = "https://zitcoin.io/nftjson/" + split[0]+".json";
            TransactionReceipt transactionReceipt = contract.safeMint(recipientAddress, tokenId, url).send();
            // 处理交易收据
            return CONTRACT_ADDRESS;
        } catch (Exception e) {
            // 处理交易错误
            System.err.println("Transaction failed: " + e.getMessage());
        }
        return null;
    }


    public void nftNum() {
        for (int i = 1; i <= 3000; i++) {
            String nftName = i + ".png";
            sendNftAddService.insertNft(nftName);
        }
    }
}
